﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.DataAccess;
using YiYiTong.Rocket.EFDBFirst;
using System.IO;
using YiYiTong.Rocket.Business.Biz;
using ServiceStack.Redis;
using YiYiTong.Rocket.Model.Model;
using System.Timers;
using System.Threading.Tasks;

namespace YiYiTong.Rocket.Business
{
    public class SessionBiz
    {
        #region 单例模式
        private SessionBiz()
        {
        }

        private static SessionBiz _instance;
        private static readonly object _syncObject = new object();

        public static SessionBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new SessionBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式
        /// <summary>
        /// 订阅消息
        /// </summary>
        public void Subscription()
        {
            var consumer = RedisPoolManager.Instance.GetClient();

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            string msgchannel = "userrequestchannel";
            //创建订阅
            ServiceStack.Redis.IRedisSubscription subscription = consumer.CreateSubscription();

            //接收消息处理Action
            subscription.OnMessage = (channel, msg) =>
            {
                if (!string.IsNullOrWhiteSpace(msg) && msg != "{}")
                {
                    try
                    {
                        SessionModel sessionModel = JsonHelper.Deserialize<SessionModel>(msg);
                        dbcontext.ADZ_ApiRequestInfo.Add(
                            new ADZ_ApiRequestInfo
                            {
                                channel = sessionModel.httpRequest.channel,
                                create_time = DateTime.Now,
                                data = sessionModel.httpRequest.data,
                                ip = sessionModel.ip,
                                machineCode = sessionModel.httpRequest.machineCode,
                                merNo = sessionModel.httpRequest.merNo,
                                service = sessionModel.httpRequest.service,
                                sign = sessionModel.httpRequest.sign,
                                timeStamp = sessionModel.httpRequest.timeStamp,
                                token = sessionModel.httpRequest.token,
                                uid = sessionModel.uid,
                                version = sessionModel.httpRequest.version
                            });
                        dbcontext.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error(ex.GetExcetionMessage());
                    }
                }
            };

            //订阅事件处理
            subscription.OnSubscribe = (channel) =>
            {
                Console.WriteLine("订阅客户端：开始订阅" + channel);
            };

            //取消订阅事件处理
            subscription.OnUnSubscribe = (a) => { Console.WriteLine("订阅客户端：取消订阅"); };


            //模拟：发送100条消息给服务
            Task.Run(() =>
            {
                HeartBreath(subscription);
            });

            //订阅频道
            subscription.SubscribeToChannels(msgchannel);

        }

        public void HeartBreath(IRedisSubscription subscription)
        {
            Timer timer1 = new Timer();
            timer1.Elapsed += new ElapsedEventHandler(
                (obj, eventArg) =>
                {
                    if (subscription == null || subscription.SubscriptionCount <= 0)
                    {
                        Console.WriteLine("订阅已经停止，请重启");
                        Subscription();
                    }
                    else
                    {
                        using (ServiceStack.Redis.IRedisClient publisher = RedisPoolManager.Instance.GetClient())
                        {
                            Console.WriteLine("发送心跳："+DateTime.Now.ToString(1));
                            publisher.PublishMessage("userrequestchannel", "{}");
                        }
                    }
                });
            timer1.Interval = 60000;//毫秒 1秒=1000毫秒
            timer1.Enabled = true;//必须加上
            timer1.AutoReset = true;//执行一次 false，一直执行true 
            timer1.Start();
        }
    }
}
